﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace MSpecLauncher.Services
{
    /// <summary>
    /// Timer that executes a callback in a different thread,
    /// usinginternally the class System.Threading.Timer
    /// </summary>
    public class AsyncTimer : IAsyncTimer
    {
        private Timer timer = null;
        private long period;

        public AsyncTimer(long period)
        {
            this.period = period;
        }

        /// <summary>
        /// Starts the timer with the given callback
        /// </summary>
        public void Start(Action<object> callback, object prm)
        {
            // Create new timer object
            this.timer = new Timer(new TimerCallback(callback), prm, 0, this.period);
        }

        /// <summary>
        /// Stops the timer
        /// </summary>
        public void Stop()
        {
            if (this.timer != null)
            {
                this.timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                this.timer = null;
            }
        }

        /// <summary>
        /// Gets if the timer is started
        /// </summary>
        public bool IsStarted
        {
            get { return this.timer != null; }
        }

    }
}
